package com.chendx.store.order.mq.listener;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.chendx.model.order.pojo.Order;
import com.chendx.model.order.pojo.OrderItem;
import com.chendx.model.order.vo.OrderNotice;
import com.chendx.model.user.pojo.UserPref;
import com.chendx.store.common.constants.ampq.AMQPConstants;
import com.chendx.store.common.constants.cart.CartConstants;
import com.chendx.store.common.constants.order.OrderConstants;
import com.chendx.store.order.feign.GoodsFeign;
import com.chendx.store.order.service.OrderItemService;
import com.chendx.store.order.service.OrderService;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * Created by chendx on 2022/4/24.
 */
@RabbitListener(queues = "queue.storeOrdertimer")
@Component
public class OrderMessageListener {

    @Autowired
    private GoodsFeign goodsFeign;
    @Autowired
    private OrderItemService orderItemService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private Environment env;

    @Transactional
    @RabbitHandler
    public void reciver(String message){
        String[] messages = message.split(",");
        String type = messages[0];
        if (type.equals("order")) {
            System.out.println("回滚");
            Object orderObj = redisTemplate.boundHashOps(OrderConstants.ORDERLIST).get(messages[1]);
            if (orderObj == null){
                return;
            }
            Order order = JSON.parseObject(orderObj.toString(), Order.class);
            if (order == null || order.getPayStatus().equals("1")){
                return;
            }
            order.setPayStatus("3");
            order.setOrderStatus("3");
            order.setCloseTime(new Date());
            orderService.updateById(order);
            List<OrderItem> orderItems = orderItemService.list(Wrappers.<OrderItem>lambdaQuery().eq(OrderItem::getOrderId, order.getId()));
            for (OrderItem orderItem : orderItems){
                goodsFeign.incrCount(orderItem);
            }
            String image = null;
            try {
                image = orderItems.get(0).getImage();
            } catch (IndexOutOfBoundsException e) {
                e.printStackTrace();
                return;
            }
            redisTemplate.boundHashOps(OrderConstants.ORDERLIST).delete(messages[1]);
            if (!order.getPrefId().equals("0")){
                Object userPrefObj = redisTemplate.boundHashOps(CartConstants.RECEIVER_PREF + order.getUsername()).get(order.getPrefId());
                if (userPrefObj != null){
                    UserPref userPref = JSON.parseObject(userPrefObj.toString(),UserPref.class);
                    userPref.setStatus("0"); //返还代金券
                    redisTemplate.boundHashOps(CartConstants.RECEIVER_PREF + order.getUsername()).put(order.getPrefId(), JSON.toJSONString(userPref));
                }
            }
            Object noticeObj = redisTemplate.boundHashOps(OrderConstants.ORDER_NOTICE_USER + order.getUsername()).get(order.getId());
            if (noticeObj == null){
                return;
            }
            OrderNotice orderNotice = JSON.parseObject(noticeObj.toString() , OrderNotice.class);
            orderNotice.setTitle("订单关闭通知");
            orderNotice.setContent("订单超时，关闭订单。");
            orderNotice.setState("0");
            orderNotice.setCreateTime(new Date());
            orderNotice.setOrderImg(image);
            redisTemplate.boundHashOps(OrderConstants.ORDER_NOTICE_USER + order.getUsername()).put(order.getId(),JSON.toJSONString(orderNotice));
            rabbitTemplate.convertAndSend(env.getProperty(AMQPConstants.MQ_ORDER_EXCHANGE_ORDERPAYNOTICE), order.getUsername(),JSON.toJSONString(order));
        }
    }
}
